package com.dmwork.service.interaction.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmwork.common.base.result.R;
import com.dmwork.service.interaction.entity.FeedComment;
import com.dmwork.service.interaction.entity.vo.FeedCommentVo;
import com.dmwork.service.interaction.feign.CustomerFeignService;
import com.dmwork.service.interaction.mq.sender.MessageSender;
import com.dmwork.service.interaction.service.FeedCommentService;
import com.vdurmont.emoji.EmojiParser;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Transactional
@RestController
@RequestMapping("/admin/dm_work/interaction/feed_comment")
public class AdminFeedCommentController {

    @Autowired
    private FeedCommentService feedCommentService;
    @Autowired
    private CustomerFeignService customerFeignService;
    @Autowired
    private MessageSender messageSender;

    @ApiOperation("获取当前动态详情下的所有对动态的评论")
    @GetMapping("get_comment_list/{feedId}/{sortType}/{page}/{limit}")
    public R getCommentList(@PathVariable String feedId, @PathVariable Integer sortType, @PathVariable Integer page, @PathVariable Integer limit) {
        Page<FeedComment> feedCommentPage = feedCommentService.getCommentPage(feedId, sortType, page, limit);
        if (feedCommentPage.getTotal() == 0) {
            return R.ok().message("暂无回复");
        }
        List<String> customerIdList = new ArrayList<>();
        for (FeedComment feedComment : feedCommentPage.getRecords()) {
            customerIdList.add(feedComment.getCustomerId());
        }
        R result = customerFeignService.getBriefInfoList(customerIdList);
        if (!result.getSuccess()) {
            return R.error().message("获取失败");
        }
        Map<String, Object> resultData = (Map<String, Object>) result.getData().get("result");
        List<FeedCommentVo> feedCommentVoList = new ArrayList<>();
        for (FeedComment feedComment : feedCommentPage.getRecords()) {
            FeedCommentVo feedCommentVo = new FeedCommentVo();
            //转换Emoji
            if (!StringUtils.isEmpty(feedCommentVo.getContent())) {
                feedCommentVo.setContent(EmojiParser.parseToUnicode(feedCommentVo.getContent()));
            }
            BeanUtils.copyProperties(feedComment, feedCommentVo);
            ArrayList<String> info = (ArrayList<String>) resultData.get(feedComment.getCustomerId());
            feedCommentVo.setCustomerName(info.get(0));
            feedCommentVo.setAvatar(info.get(1));

            //查询当前的动态评论下有多少条回复
            int count = feedCommentService.count(new QueryWrapper<FeedComment>().eq("parent_comment_id", feedComment.getId()));
            feedCommentVo.setReplyCount(count);
            feedCommentVoList.add(feedCommentVo);
        }
        return R.ok().data("total", feedCommentPage.getTotal()).data("rows", feedCommentVoList);
    }

    @ApiOperation("获取指定的动态评论下的多条回复评论")
    @GetMapping("get_reply_list/{commentId}/{sortType}/{page}/{limit}")
    public R getReplyList(@PathVariable String commentId, @PathVariable Integer sortType, @PathVariable Integer page, @PathVariable Integer limit) {
        Page<FeedComment> feedCommentPage = feedCommentService.getReplyPage(commentId, sortType, page, limit);
        if (feedCommentPage.getTotal() == 0) {
            return R.ok().message("暂无回复");
        }
        //获取每条评论的所属用户的用户名和头像，若该评论所回复的评论也是一条回复，则获取该评论所属用户的用户名
        List<String> customerIdList = new ArrayList<>(); //评论所属用户id
        List<String> repliedCustomerIdList = new ArrayList<>(); //被回复者用户id
        for (FeedComment feedComment : feedCommentPage.getRecords()) {
            customerIdList.add(feedComment.getCustomerId());
            //RepliedCommentId和ParentCommentId相等，说明是直接回复动态评论，否则是对评论下其它回复的一条回复
            if (!feedComment.getRepliedCommentId().equals(feedComment.getParentCommentId())) {
                repliedCustomerIdList.add(feedComment.getRepliedCustomerId());
            }
        }
        R customerResult = customerFeignService.getBriefInfoList(customerIdList); //获取评论所属用户信息
        R repliedCustomerResult = null;
        if (!repliedCustomerIdList.isEmpty()) { //获取被回复者用户信息
            repliedCustomerResult = customerFeignService.getBriefInfoList(repliedCustomerIdList);
            if (!customerResult.getSuccess() || !repliedCustomerResult.getSuccess()) {
                return R.error().message("获取失败");
            }
        }
        Map<String, Object> customerResultData = (Map<String, Object>) customerResult.getData().get("result");
        Map<String, Object> repliedCustomerResultData = null;
        if (repliedCustomerResult != null) {
            repliedCustomerResultData = (Map<String, Object>) repliedCustomerResult.getData().get("result");
        }
        List<FeedCommentVo> feedCommentVoList = new ArrayList<>();
        for (FeedComment feedComment : feedCommentPage.getRecords()) {
            FeedCommentVo feedCommentVo = new FeedCommentVo();
            //转换Emoji
            if (!StringUtils.isEmpty(feedCommentVo.getContent())) {
                feedCommentVo.setContent(EmojiParser.parseToUnicode(feedCommentVo.getContent()));
            }
            BeanUtils.copyProperties(feedComment, feedCommentVo);
            ArrayList<String> customerInfoList = (ArrayList<String>) customerResultData.get(feedComment.getCustomerId());
            feedCommentVo.setCustomerName(customerInfoList.get(0)); //获取用户名
            feedCommentVo.setAvatar(customerInfoList.get(1)); //获取头像
            if (repliedCustomerResultData != null && !feedComment.getRepliedCommentId().equals(feedComment.getParentCommentId())) {
                ArrayList<String> repliedCustomerInfoList = (ArrayList<String>) repliedCustomerResultData.get(feedComment.getRepliedCustomerId());
                feedCommentVo.setRepliedCustomerName(repliedCustomerInfoList.get(0)); //获取用户名
            }

            feedCommentVoList.add(feedCommentVo);
        }
        return R.ok().data("total", feedCommentPage.getTotal()).data("rows", feedCommentVoList);
    }

    @ApiOperation("删除指定评论")
    @DeleteMapping("remove_comment/{commentId}")
    public R removeComment(@PathVariable String commentId) {
        FeedComment feedComment = feedCommentService.getById(commentId);
        feedCommentService.removeById(commentId);
        messageSender.sendCommentMessage(feedComment.getRepliedCustomerId(), commentId, 1, 0);
        return R.ok().message("删除成功");
    }

}
